package com.shangye.http;


import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpServletRequest {

    private Socket socket;

    private String method;
    private String uri;
    private String protocol;
    private Map<String,String> headers = new HashMap();

    public HttpServletRequest(Socket socket) {
        this.socket = socket;

        // 1,解析请求行
        parseRequesrtLine();
        // 2,解析消息头
        parseHeaders();
        // 3，解析消息正文
        parseContent();
    }

    // 1,解析请求行
    private void parseRequesrtLine() {
        try {
            //  读取请求行
            String line = redLine();
            System.out.println("请求行：" + line);
            //  解析请求行：
            String[] split = line.split("\\s");
            method = split[0];
            uri = split[1];
            protocol = split[2];
            System.out.println("请求方式：" + method);
            System.out.println("请求路径：" + uri);
            System.out.println("协议版本：" + protocol);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 2,解析消息头
    private void parseHeaders() {
        try {
            while (true) {
                String line = redLine();
                if (line.isEmpty()) {
                    break;
                }
                System.out.println("消息头：" + line);
                String[] split = line.split(": ");
                headers.put(split[0], split[1]);
            }
            System.out.println("消息头MAP：" + headers);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 3，解析消息正文
    private void parseContent() {

    }

    private String redLine() throws Exception {
        InputStream is = socket.getInputStream();

        char pre = 'a', cur = 'a';
        StringBuilder builder = new StringBuilder();
        int d;
        while ((d = is.read()) != -1) {
            cur = (char) d;
            if (pre == 13 && cur == 10) {
                break;
            } else {
                pre = cur;
                builder.append(cur);
            }
        }
        String line = builder.toString().trim();
        return line;


    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    public String getHeaders(String key) {
        return headers.get(key);
    }
}
